#!/usr/bin/env python3.10.6
# -*- coding: utf-8 -*-
# Author: Bobby Sheng <Bobby@sky-cloud.net>
from units.get_config_data import get_config_yaml_data
from units.log_control import ERROR
from feushu_api.feishu_login import tenant_access_token
import requests
import json
import time
import jsonpath


class FeishuSendMassage:

    def __init__(self, issues_info_data: dict):
        self.issues_info_data = issues_info_data
        self.Config = get_config_yaml_data()

    def get_user_id(self, name_data):
        receive_id_data = jsonpath.jsonpath(self.Config, "$.userInfo")[0]

        receive_id = [i.get("user_id") for i in receive_id_data if str(i.get("username")) == str(name_data)][0]
        return receive_id

    def sent_post(self, record_key):
        """
        发送消息（内容UTF-8编码）
        :return: 返回消息发送结果
        """
        msg_title = ''
        template = ''
        to_send_msg = False
        receive_id_list = []
        headers = tenant_access_token()
        la = "{\"config\": {\"wide_screen_mode\": true}, \"elements\": [{\"tag\": \"div\", \"text\": {\"content\": \"**类型**：${issuetype}\\n**描述**：${summary}\\n**状态**：${status}\\n**优先级**：${priority}\\n**处理人**：${assignee}\\n**报告人**：${reporter}\\n\", \"tag\": \"lark_md\"}}, {\"actions\": [{\"tag\": \"button\", \"text\": {\"content\": \"跳转工单详情\", \"tag\": \"plain_text\"}, \"type\": \"primary\", \"multi_url\": {\"url\": \"${jira_link}\", \"pc_url\": \"\", \"android_url\": \"\", \"ios_url\": \"\"}}], \"tag\": \"action\"}], \"header\": {\"template\": \"${template}\", \"title\": {\"content\": \"${status_msg}\", \"tag\": \"plain_text\"}}}"

        if str(self.issues_info_data.get("status")) == "待办":
            msg_title = "靓仔您好！您有新的Jira工单，请尽快处理哦！"
            template = "yellow"
            to_send_msg = True
            assignee = self.issues_info_data.get('assignee')
            userid = self.get_user_id(assignee)
            receive_id_list.append(userid)


        elif str(self.issues_info_data.get("status")) == "测试中":
            msg_title = "靓仔您好！您有待测试Jira工单，请尽快处理哦！"
            template = "yellow"
            to_send_msg = True
            name_list = ["张圣波", "郭紫薇"]
            for i in name_list:
                receive_id_list.append(self.get_user_id(i))


        elif str(self.issues_info_data.get("status")) == "产品验收中":
            msg_title = "靓仔您好！您有待验收Jira工单，请尽快处理哦！"
            template = "yellow"
            to_send_msg = True
            userid = self.get_user_id("杨雨")
            receive_id_list.append(userid)


        elif str(self.issues_info_data.get("status")) == "完成" and str(self.issues_info_data.get("issuetype")) == "故障":
            msg_title = "靓仔，Jira故障工单已完成，你太棒了！"
            template = "green"
            to_send_msg = True
            name_list = ["张圣波", "郭紫薇"]
            for i in name_list:
                receive_id_list.append(self.get_user_id(i))
            assignee = self.issues_info_data.get('assignee')
            userid = self.get_user_id(assignee)
            receive_id_list.append(userid)


        elif str(self.issues_info_data.get("status")) == "完成" and str(self.issues_info_data.get("issuetype")) == "故事":
            msg_title = "靓仔，Jira需求工单已完成，你太棒了！"
            template = "green"
            to_send_msg = True
            name_list = ["张圣波", "郭紫薇", "杨雨"]
            for i in name_list:
                receive_id_list.append(self.get_user_id(i))
            assignee = self.issues_info_data.get('assignee')
            userid = self.get_user_id(assignee)
            receive_id_list.append(userid)


        elif str(self.issues_info_data.get("status")) == "完成":
            msg_title = "靓仔，Jira任务/子任务工单已完成，你太棒了！"
            template = "green"
            to_send_msg = True
            assignee = self.issues_info_data.get('assignee')
            userid = self.get_user_id(assignee)
            receive_id_list.append(userid)

        else:
            ERROR.logger.error(f"{str(self.issues_info_data.get('status'))}状态不支持发送消息", )

        msg = la.replace("${summary}", f"{self.issues_info_data.get('summary')}").replace("${priority}",
                                                                                          f"{self.issues_info_data.get('priority')}").replace(
            "${status}",
            f"{self.issues_info_data.get('status')}").replace(
            "${issuetype}", f"{self.issues_info_data.get('issuetype')}").replace("${assignee}",
                                                                                 f"{self.issues_info_data.get('assignee')}").replace(
            "${reporter}", f"{self.issues_info_data.get('reporter')}").replace(
            "${status_msg}", msg_title).replace("${template}", template).replace("${jira_link}",
                                                                                 f"https://jira.sky-cloud.net/browse/{record_key}")
        result = ''
        if to_send_msg and receive_id_list:
            for receive_id in receive_id_list:
                rich_text = {
                    "receive_id": receive_id,
                    "msg_type": "interactive",
                    "content": msg
                }
                print(rich_text)
                post_data = json.dumps(rich_text)
                response = requests.post(
                    jsonpath.jsonpath(self.Config, "$.feishu.webhook")[0],
                    headers=headers,
                    data=post_data,
                    verify=False
                )
                result = response.json()
                print(result)
                if result.get('code') != 0:
                    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
                    result_msg = result['errmsg'] if result.get('errmsg', False) else '未知异常'
                    error_data = {
                        "msgtype": "text",
                        "text": {
                            "content": f"[注意-自动通知]飞书机器人消息发送失败，时间：{time_now}，"
                                       f"原因：{result_msg}，请及时跟进，谢谢!"
                        },
                        "at": {
                            "isAtAll": False
                        }
                    }
                    ERROR.logger.error("消息发送失败，自动通知：%s", error_data)
                    requests.post(jsonpath.jsonpath(self.Config, "$.feishu.webhook")[0], headers=headers,
                                  data=json.dumps(error_data))
            return result


if __name__ == '__main__':
    from jira_business.jira_status_update import search_issues_status

    issues_info_data = search_issues_status("INET-1509")
    FeishuSendMassage(issues_info_data).sent_post("INET-1509")
    # FeishuSendMassage({"status": "待办"}).sent_post("INET-1599")
